<?php

class View{
	
	public $layout = "layout";
	
	public $_vars = array();
	public $locales;
	
	public static $inst;
	
	public function __construct() {
		self::_loadLocales();
	}
	
	public static function _getInstance() {
		if(!self::$inst) {
			self::$inst = new View();
		}
		return self::$inst;
	}
	
	private function _loadLocales($lang) {
		$path = "resource/locale/$lang.locale";
		if(file_exists($path)) {
			$this->locales = array();
			
			if(!isset($_SESSION["locales"][$lang])){
				$data = file_get_contents($path);
				preg_match_all('/-{4}\r?\n(.+)\r?\n-{2}\r?\n(.+)/x', $data, $matches);
				if($matches){
					foreach($matches[1] as $k=>$key){
						$this->locales[trim($key)] = trim($matches[2][$k]);
					}
				}
				$_SESSION["locales"][$lang] = $this->locales;
			}
			
			$this->locales = $_SESSION["locales"][$lang];
		}
	}
	
	public function render($view=false) {
		$prev = ob_get_contents();
		ob_clean();
		
		$c = $this->fetch($view);
		echo $prev;
		if($this->layout){
			$this->set("__content", $c);
			echo $this->_fetch($this->layout);
		}else{
			echo $c;
		}
	}
	
	public function fetch($view=false) {
		$prev = ob_get_contents();
		ob_clean();
		if(!$view){
			$view = "{$this->request->controller}/{$this->request->action}";
		}
		echo $prev;
		return $this->_fetch($view);
	}
	
	public function _fetch($path) {
		$path = "app/views/$path.ctp";
		foreach($this->_vars as $k=>$v) {
			$$k = $v;
		}
		
		if(file_exists($path)) {
			include_once $path;
		}else{
			$missing_view = $path;
			include_once "app/views/errors/missing_view.ctp";
		}
		$ret = ob_get_contents();
		ob_clean();
		return $ret;
	}
	
	public function set($name, $value) {
		$this->_vars[$name] = $value;
	}
	
	public static function translate($text) {
		$V = self::_getInstance();
		$ret = $text;
		
		$lang = $_SESSION["language"];
		if($lang != DEFAULT_LOCALE){
			$V->_loadLocales($lang);
			if(isset($V->locales[$text])) {
				$ret = $V->locales[$text];
			}
		}
		return $ret;
	}
}